const Koa = require('koa')
const Router = require('koa-router')
const render = require('koa-art-template')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const path = require('path')

// const wechat = require('./wechat-lib/middleware')
// const reply = require('./wechat/reply')
const config = require('./config/config')
const {
  initSchema,
  connect
} = require('./app/database/db')

const app = new Koa()
const router = new Router()
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
render(app, {
  root: path.join(__dirname, './app/views'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
});
(async () => {
  await connect(config.db)
  initSchema()
})()
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
require('./routes')(router)
// app.use(wechat(config.wx, reply.reply))

// routes
app.use(router.routes()).use(router.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});
module.exports = app
